package day06.concurrent03;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Lock的优势2：可以tryLock()尝试获取锁，从而在得到锁 和 没有得到锁时 执行不同的代码
 */
public class Demo04 {
    static String name = "小明";
    static String gender = "男";
    static Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    //尝试获取锁，无论是否得到锁，都会继续执行，得到锁返回true，没得到锁返回false
                    boolean hasGetLock = lock.tryLock();
                    if(hasGetLock){
                        //如果能抢到锁 打印！
                        System.out.println(name+"#"+gender);
                        lock.unlock();
                    }else{
                        //没抢到锁 从数据库读取数据打印
                        System.out.println("###没有抢到锁！从数据库读取数据打印..大壮！男!");
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    lock.lock();
                    if("小明".equals(name)){
                        name = "小花";
                        gender = "女";
                    }else{
                        name = "小明";
                        gender = "男";
                    }
                    lock.unlock();
                }
            }
        }).start();
    }
}
